layui.config({
    base: '../js/layui/lay/modules/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
});
layui.use(['form','formSelects','layer'], function () {

    var $ = layui.$, form = layui.form, formSelects = layui.formSelects, layer=layui.layer;

    var positionList;
    var userInfo;
    $(function () {
        LoginStatus();

        userInfo = JSON.parse($.cookie('userInfo'));

        $('#userAvatar').attr('src', companyServices + userInfo.img);
        $('#userName').text((userInfo.name == '' || userInfo.name == null) ? "":userInfo.name);
        $('#userNameOther').text((userInfo.name == '' || userInfo.name == null) ? "":userInfo.name);
        $('#userPhone').text((userInfo.tel == '' || userInfo.tel == null) ? "":userInfo.tel);
        $('#userPosition').text(userInfo.position == '' ? '人事': userInfo.position);

        //加载公司信息
        loadCompany();
        //加载职位信息
        loadPositionList();
    })


    form.on('submit(btnSave)', function (data) {

        data.field.skillRequirement = formSelects.value('skillRequirement', 'valStr');
        data.field.city = formSelects.value('expectCity', 'valStr');

        layer.load(2);

        var method = 'put';
        if (data.field.id != null && data.field.id != '' && data.field.id != 'undefined') {
            method = 'post';
        }

        $.ajax({
            type: method, // 提交方式 get/post
            url: companyServices+"/position", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:JSON.stringify(data.field),
            success: function(res) {
                layer.closeAll('loading');
                if(res.status == '00200'){
                    layerMsg(res.message);
                    setTimeout(function() {
                        window.location.href="job-manage.html" ;
                    }, 2000);

                }else{
                    layerMsg(res.message)
                }
            },fail:function () {
                layer.closeAll('loading');
            }
        })
        return false;
    });


    $('.job-list ul').on('click', 'li', function(e){
        var index = $(this).attr('data-index');
        if (isMobile()) {
            window.location.href="wrap-edit-position.html?id="+positionList[index].id;
        } else {
            if (e.target.localName == 'a') {
                layer.confirm('是否确认删除该职位？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    delPosition(positionList[index].id);
                }, function(){

                });
            } else {
                var index = $(this).attr('data-index');
                $('.job-list ul li').removeClass('curr');
                $(this).addClass('curr');

                initForm(positionList[index]);
            }
        }
    });

    $('#delPosition').click(function () {
        layer.confirm('是否确认删除该职位？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            var id = $('#id').val();
            delPosition(id);
        }, function(){

        });

    })

    function delPosition(positionId) {
        var ids = [];
        ids.push(positionId);

        layer.load(2);
        $.ajax({
            type: 'delete', // 提交方式 get/post
            url: companyServices+"/position", // 需要提交的 url
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data: {"ids":ids.join(",")}
            ,success: function(res) {
                layer.closeAll('loading');
                if(res.status == '00200'){
                    layerMsg(res.message);
                    setTimeout(function() {
                        window.location.href="job-manage.html" ;
                    }, 2000);

                }else{
                    layerMsg(res.message)
                }
            },fail:function () {
                layer.closeAll('loading');
            }
        })
    }

    $('#addPosition').click(function () {
        if (isMobile()) {
            window.location.href="wrap-edit-position.html";
        } else {
            // layui.use(['treeSelect','form'], function () {
            //     var treeSelect= layui.treeSelect;
            //     treeSelect.destroy('tree')
            // });
            // setTimeout(function(){
                $('.job-list ul li').removeClass('curr');
                initForm(null);
            // },0)

        }
    })

    $('#addPositionOther').click(function () {
        if (isMobile()) {
            window.location.href="wrap-edit-position.html";
        } else {
            // layui.use(['treeSelect','form'], function () {
            //     var treeSelect= layui.treeSelect;
            //     treeSelect.destroy('tree')
            // });
            // setTimeout(function(){
                $('.job-list ul li').removeClass('curr');
                initForm(null);
            // },0)

        }
    })

    //加载公司信息
    function loadCompany() {
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/company", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                checkLoginStatus(res);

                if(res.status == '00200'){
                    var companyInfo = res.data;
                    //$.cookie("companyInfo", JSON.stringify(companyInfo));
                    $('#companyLogo').attr('src', companyServices + companyInfo.logo);
                    $('#companyFullName').text((companyInfo.fullName == '' || companyInfo.fullName == null) ? "":companyInfo.fullName);
                    $('#companySimpleName').text((companyInfo.simpleName == '' || companyInfo.simpleName == null) ? "":companyInfo.simpleName);
                    $('#industry').text((companyInfo.industryName == '' || companyInfo.industryName == null) ? "":companyInfo.industryName);
                    $('#companyLevel').text((companyInfo.companySizeLevelName == '' || companyInfo.companySizeLevelName == null) ? "":companyInfo.companySizeLevelName);

                    if (companyInfo.rootId === userInfo.id) {
                        $('#hrManager').show();
                    }
                }
            }
        })
    }

    //加载职位列表
    function loadPositionList() {
        layer.load(2);
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/position/list?page=1&limit=200", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                layer.closeAll('loading');
                checkLoginStatus(res);

                if(JSON.parse(res).code == '0'){
                    positionList = JSON.parse(res).data;

                    var html = '';
                    if (positionList != null && positionList.length > 0) {
                        $.each(positionList, function (index, item) {
                            if (index == 0) {
                                html += '<li class="curr" data-index="'+index+'">';
                            } else {
                                html += '<li  data-index="'+index+'">';
                            }

                            html += '<h2>';
                            html += item.positionName + '<span>'+dateFormat("yyyy-MM-dd",new Date(item.updateTime))+'</span>';
                            html += '</h2>';
                            html += '<p class="job-demand">'
                            html += '<span>'+((item.workCity == "" || item.workCity == null) ? "":item.workCity)+'</span>|<span>'+((item.workExperienceLevelName == "" || item.workExperienceLevelName == null) ? "":item.workExperienceLevelName)+'</span>|<span>'+((item.educationLevelName == "" || item.educationLevelName == null) ? "":item.educationLevelName)+'</span>';
                            /*html += '<span>'+item.workCity+'</span>|<span>'+item.workAddress+'</span>|<span>'+item.workExperienceLevelName+'</span>|<span>'+item.educationLevelName+'</span>';*/
                            html += '<a href="javascript:">删除</a>';
                            html += '</p>';
                            html += '<p class="pay">'+((item.salaryLevelName == "" || item.salaryLevelName==null) ? "":item.salaryLevelName)+'</p>';
                            html += '</li>';
                        })

                        $('#positionList').html(html);
                        initForm(positionList[0]);
                    } else {
                        initForm(null);
                    }
                }
            }, fail:function () {
                layer.closeAll('loading');
            }
        })
    }
    $('#logout').click(function () {
        layer.confirm('您确认退出登录吗？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            logoutCompany();
        }, function(){

        });
    })

    function initForm(obj) {
        layui.use(['treeSelect','form'], function () {
            var treeSelect= layui.treeSelect;
            treeSelect.destroy('tree')
        });
        if (obj != null) {
            $('#id').val(obj.id);
            $('#positionName').val(obj.positionName);
            $('#workAddress').val(obj.workAddress);
            $('#recruitNumber').val(obj.recruitNumber);
            $('#workDescription').val(obj.workDescription);
            $('#otherSkillRequirement').val(obj.otherSkillRequirement);
            $('#otherWorkAddress').val(obj.otherWorkAddress);
            $('#ageRequirement').val(obj.ageRequirement);


            //重置薪酬范围
            loadSalaryLevel(obj.salaryLevel);
            //重置城市
            loadCity(obj.workCityId);
            //重置工作经验
            loadWorkExperienceLevel(obj.workExperienceLevel);
            //重置学历
            loadEducationLevel(obj.educationLevel);
            //重置年龄
            //loadAgeLevel(obj.ageLevel);
            //重置技能
            loadSkillRequirement(obj.skillRequirement)

            $('#delPosition').show();
        } else {
            $('#id').val('');
            $('#positionName').val('');
            //$('#workAddress').val('');
            $('#recruitNumber').val('0');
            $('#workDescription').val('');

            $('#workAddress').val('');
            $('#otherSkillRequirement').val('');
            $('#otherWorkAddress').val('');
            $('#ageRequirement').val('');

            //重置薪酬范围
            loadSalaryLevel(null);
            //重置城市
            loadCity(null);
            //重置工作经验
            loadWorkExperienceLevel(null);
            //重置学历
            loadEducationLevel(null);
            //重置年龄
            //loadAgeLevel(null);
            //重置技能
            loadSkillRequirement(null)

            $('#delPosition').hide();
        }
    }


    //加载薪酬范围
    function loadSalaryLevel(selectId) {
        loadSelectData('salaryLevel', selectId, "/prop/salaryLevel/list?page=1&limit=200");
    }

    function loadSkillRequirement(selectId) {
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/prop/skill/list?page=1&limit=200", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                checkLoginStatus(res);
                formSelects.data('skillRequirement', 'local', {
                    arr:JSON.parse(res).data,
                    keyName:'skillName',
                    keyVal:'id'
                });

                if (selectId != null) {
                    formSelects.value('skillRequirement', selectId.split(','));
                }
            }
        })
    }

    //加载城市
    function loadCity(selectId) {
        //formSelect(selectId, formSelects,'expectCity','get','/prop/city/list?page=0&limit=2000','cityname',false);
        //tip(formSelects,'expectCity')
        

        //加载树
        // $.ajax({
        //     type: 'get', // 提交方式 get/post
        //     url: companyServices+"/prop/city/tree", // 需要提交的 url
        //     contentType:"application/json;charset=utf-8",
        //     xhrFields: {
        //         withCredentials: true
        //     }
        //     ,crossDomain: true
        //     ,data:{},
        //     success: function(res) {
        //         checkLoginStatus(res);
        //         formSelects.data('expectCity', 'local', {
        //             arr:JSON.parse(res).data
        //         },);

        //         if (selectId != null) {
        //             formSelects.value('expectCity', selectId.split(','));
        //         }
        //     }
        // })

        layui.use(['treeSelect','form','layer'], function () {
            var treeSelect= layui.treeSelect;

            treeSelect.render({
                // 选择器
                elem: '#expectCity',
                // 数据
                data: companyServices+"/prop/city/tree",
                // 异步加载方式：get/post，默认get
                type: 'get',
                // 占位符
                placeholder: '请选择城市',
                // 是否开启搜索功能：true/false，默认false
                search: false,
                // 点击回调
                click: function(d){
                    $("input[name='workCityId']").val(d.current.value)
                },
                // 加载完成后的回调函数
                success: function (d) {
                    if(selectId){
                        console.log("selectId:"+typeof(selectId))
                        treeSelect.checkNode('tree', selectId);
                        $("input[name='workCityId']").val(selectId)
                    }else{
                        if($("input[name='workCityId']").val()!=null||$("input[name='workCityId']").val()!=""){
                            selectId = $("input[name='workCityId']").val();
                            treeSelect.checkNode('tree',selectId);
                            $("input[name='workCityId']").val(selectId)
                        }
                    }
                
                }
            });
        });
    }

    //加载经验列表
    function loadWorkExperienceLevel(selectId) {
        loadSelectData('workExperienceLevel', selectId, "/prop/workExperienceLevel/list?page=1&limit=200");
    }

    //加载加载年龄列表
    function loadAgeLevel(selectId) {
        loadSelectData('ageLevel', selectId, "/prop/ageLevel/list?page=1&limit=200");
    }

    //加载学历层级
    function loadEducationLevel(selectId) {
        loadSelectData('educationLevel', selectId, "/prop/educationLevel/list?page=1&limit=200");
    }
    //加载下拉选项并选中，如果selectId存在并且相等
    function loadSelectData(selectName, selectId, url) {

        var html = '<option value="">请选择</option>';

        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+url, // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                //checkLoginStatus(res);
                if (JSON.parse(res).data != null) {
                    $.each(JSON.parse(res).data, function (index, item) {
                        if (selectId != null && selectId != '' && selectId == item.id) {
                            html += '<option value="'+item.id+'" selected>'+item.name+'</option>';
                        } else {
                            html += '<option value="'+item.id+'">'+item.name+'</option>';
                        }
                    })
                    $('#' + selectName).html(html);
                    form.render();

                }

            }
        })



    }


    /**************************************时间格式化处理************************************/
    function dateFormat(fmt,date) {
        var o = {
            "M+" : date.getMonth()+1,                 //月份
            "d+" : date.getDate(),                    //日
            "h+" : date.getHours(),                   //小时
            "m+" : date.getMinutes(),                 //分
            "s+" : date.getSeconds(),                 //秒
            "q+" : Math.floor((date.getMonth()+3)/3), //季度
            "S"  : date.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    }


    function formSelect(selectId,formSelects,_id,_type,_url,_name,Insert=true,Inserturl="",array=[]){
        formSelects.config(_id, {
            type: _type,                //请求方式: post, get, put, delete...
            searchName: _name,      //自定义搜索内容的key值
            searchVal: '',              //自定义搜索内容, 搜素一次后失效, 优先级高于搜索框中的值
            keyName: _name,            //自定义返回数据中name的key, 默认 name
            searchUrl: companyServices+_url,
            keyVal: 'id',            //自定义返回数据中value的key, 默认 value
            delay: 500,  //搜索延迟时间, 默认停止输入500ms后开始搜索\
            response: {
                statusCode: 0,          //成功状态码
                statusName: 'code',     //code key
                msgName: 'msg',         //msg key
                dataName: 'data'  ,      //data key
            },
            beforeSuccess: function(id, url, searchVal,result){
                if(result.code==0){
                    if(result.count==0){
                        result.code = 201;
                        result.msg = "没有找到选项";
                        if(Insert){
                            btns(formSelects,id,_url,array,searchVal,Inserturl,'put',_name);
                        }
                    }
                }
                return result;  //必须return一个结果, 这个结果要符合对应的数据结构
            },
            error: function(id, url, searchVal, err){           //使用远程方式的error回调
                //同上
                console.log(err);   //err对象
            },
            success:function () {
                if (selectId != null) {
                    if (_id == 'expectCity') {
                        formSelects.value(_id, selectId.toString().split(','));
                    } else {
                        formSelects.value(_id, selectId.split(","));
                    }

                }
            }
        }, false)
    }

    function InsertApi(_addurl,_addtype,_name,_value){
        var arrdata = {};
        arrdata[_name] = _value;
        arrdata["pid"] = '0';
        var result = ""
        $.ajax({
            type: _addtype, // 提交方式 get/post
            url:companyServices+_addurl,
            contentType:"application/json;charset=utf-8",
            async:false,
            // contentType:"application/json;charset=utf-8",
            //解决跨域
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data:JSON.stringify(arrdata),
            success: function(res) {
                result = JSON.stringify(res);
                ApiLoginStatus(result)
                if(res.success){
                    result = res;
                }
            },
        });
        return result;

    }

    function localAPi(formSelects,_id,searchVal,key,value,timestamp,array){

        var arr = {};
        arr[key]=timestamp;
        arr[value]=searchVal;
        array.push(arr)
        //local模式
        formSelects.data(_id, 'local', {
            arr:array
        });
        return array;
    }

    function serviceAPI(formSelects,_id,_url){
        formSelects.data(_id, 'server', {
            url:companyServices+_url
        });
    }

    function btns(formSelects,_id,_url,array,_value="",_addurl="",_addtype="",_name=""){
        formSelects.btns(_id, ['select', 'remove', {
            icon: 'layui-icon layui-icon-ok',   //自定义图标, 可以使用layui内置图标
            name: '添加',
            click: function(id){
                if(_value){
                    var res = InsertApi(_addurl,_addtype,_name,_value)
                    if(res.success){
                        idvalue = res.data.id;
                        localAPi(formSelects,_id,_value,'id',_name,idvalue,array)
                    }
                }
            }
        }]);

    }
    function search(formSelects,_id,keyword){
        //使用js主动触发搜索
        formSelects.search(_id, keyword);
    }

    function arrayAjax(_url,_type){
        var array = [];
        $.ajax({
            type: _type, // 提交方式 get/post
            url:companyServices+_url,
            async:false,
            // contentType:"application/json;charset=utf-8",
            //解决跨域
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                var obj = JSON.parse(res)
                if(obj.code==0){
                    array = obj.data;
                }
            }
        })
        return array;
    }


    function tip(formSelects,selectID){
        formSelects.maxTips(selectID, function(id, vals, val, max){
            //id:   点击select的id
            //vals: 当前select已选中的值
            //val:  当前select点击的值
            //max:  当天多选最大值
            layerMsg("最多只能选择"+max+"个选项")
        });
    }

});






